using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using TMPro;
#if UNITY_EDITOR
using UnityEditor;
using UnityEditor.SceneManagement;

/// <summary>
/// 自动创建五子棋游戏场景和预制体的编辑器脚本
/// 使用方法: Unity 菜单 -> Gobang -> Setup Scene
/// </summary>
public class SceneSetup : EditorWindow
{
    [MenuItem("Gobang/Setup Scene and Prefabs")]
    public static void SetupAll()
    {
        if (EditorUtility.DisplayDialog("创建游戏场景", 
            "这将创建:\n1. MainScene 场景\n2. LinePrefab 预制体\n3. PiecePrefab 预制体\n\n是否继续?", 
            "是", "否"))
        {
            CreatePrefabs();
            CreateMainScene();
            EditorUtility.DisplayDialog("完成", "场景和预制体创建完成！\n\n请检查:\n- Assets/Scenes/MainScene.unity\n- Assets/Prefabs/LinePrefab.prefab\n- Assets/Prefabs/PiecePrefab.prefab", "确定");
        }
    }

    static void CreatePrefabs()
    {
        // 创建 LinePrefab
        GameObject line = new GameObject("Line");
        RectTransform lineRect = line.AddComponent<RectTransform>();
        lineRect.sizeDelta = new Vector2(100, 2);
        
        Image lineImage = line.AddComponent<Image>();
        lineImage.color = Color.black;
        lineImage.raycastTarget = false;
        
        string linePath = "Assets/Prefabs/LinePrefab.prefab";
        PrefabUtility.SaveAsPrefabAsset(line, linePath);
        DestroyImmediate(line);
        Debug.Log("创建 LinePrefab 完成: " + linePath);

        // 创建 PiecePrefab
        GameObject piece = new GameObject("Piece");
        RectTransform pieceRect = piece.AddComponent<RectTransform>();
        pieceRect.sizeDelta = new Vector2(40, 40);
        
        Image pieceImage = piece.AddComponent<Image>();
        pieceImage.color = Color.black;
        pieceImage.raycastTarget = false;
        
        // 使用 Unity 内置的圆形 Sprite
        pieceImage.sprite = AssetDatabase.GetBuiltinExtraResource<Sprite>("UI/Skin/Knob.psd");
        pieceImage.type = Image.Type.Simple;
        pieceImage.preserveAspect = true;
        
        string piecePath = "Assets/Prefabs/PiecePrefab.prefab";
        PrefabUtility.SaveAsPrefabAsset(piece, piecePath);
        DestroyImmediate(piece);
        Debug.Log("创建 PiecePrefab 完成: " + piecePath);
    }

    static void CreateMainScene()
    {
        // 创建新场景
        var scene = EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Single);
        
        // 创建 Canvas
        GameObject canvasObj = new GameObject("Canvas");
        Canvas canvas = canvasObj.AddComponent<Canvas>();
        canvas.renderMode = RenderMode.ScreenSpaceOverlay;
        
        CanvasScaler scaler = canvasObj.AddComponent<CanvasScaler>();
        scaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
        scaler.referenceResolution = new Vector2(1920, 1080);
        scaler.matchWidthOrHeight = 0.5f;
        
        canvasObj.AddComponent<GraphicRaycaster>();
        
        // 创建 EventSystem
        if (FindObjectOfType<EventSystem>() == null)
        {
            GameObject eventSystem = new GameObject("EventSystem");
            eventSystem.AddComponent<EventSystem>();
            eventSystem.AddComponent<StandaloneInputModule>();
        }
        
        // 创建 NetworkManager
        GameObject networkManager = new GameObject("NetworkManager");
        networkManager.transform.SetParent(canvasObj.transform, false);
        networkManager.AddComponent<NetworkManager>();
        
        // 创建 GameManager
        GameObject gameManager = new GameObject("GameManager");
        gameManager.transform.SetParent(canvasObj.transform, false);
        gameManager.AddComponent<GameManager>();
        gameManager.AddComponent<UIManager>();
        
        // 创建 LoginPanel
        CreateLoginPanel(canvasObj.transform);
        
        // 创建 MainMenuPanel
        CreateMainMenuPanel(canvasObj.transform);
        
        // 创建 MatchingPanel
        CreateMatchingPanel(canvasObj.transform);
        
        // 创建 GamePanel
        CreateGamePanel(canvasObj.transform);
        
        // 创建 GameOverPanel
        CreateGameOverPanel(canvasObj.transform);
        
        // 创建 MessagePanel
        CreateMessagePanel(canvasObj.transform);
        
        // 保存场景
        string scenePath = "Assets/Scenes/MainScene.unity";
        EditorSceneManager.SaveScene(scene, scenePath);
        Debug.Log("创建 MainScene 完成: " + scenePath);
    }

    static GameObject CreatePanel(Transform parent, string name, bool active = false)
    {
        GameObject panel = new GameObject(name);
        panel.transform.SetParent(parent, false);
        
        RectTransform rect = panel.AddComponent<RectTransform>();
        rect.anchorMin = Vector2.zero;
        rect.anchorMax = Vector2.one;
        rect.sizeDelta = Vector2.zero;
        
        Image image = panel.AddComponent<Image>();
        image.color = new Color(0.17f, 0.24f, 0.31f, 0.95f); // 半透明深色背景
        
        panel.SetActive(active);
        return panel;
    }

    static GameObject CreateButton(Transform parent, string name, string text, Vector2 position, Vector2 size)
    {
        GameObject button = new GameObject(name);
        button.transform.SetParent(parent, false);
        
        RectTransform rect = button.AddComponent<RectTransform>();
        rect.anchoredPosition = position;
        rect.sizeDelta = size;
        
        Image image = button.AddComponent<Image>();
        image.color = new Color(0.2f, 0.6f, 0.86f, 1f); // 蓝色
        
        Button btn = button.AddComponent<Button>();
        
        // 创建按钮文字
        GameObject textObj = new GameObject("Text");
        textObj.transform.SetParent(button.transform, false);
        
        RectTransform textRect = textObj.AddComponent<RectTransform>();
        textRect.anchorMin = Vector2.zero;
        textRect.anchorMax = Vector2.one;
        textRect.sizeDelta = Vector2.zero;
        
        TextMeshProUGUI tmp = textObj.AddComponent<TextMeshProUGUI>();
        tmp.text = text;
        tmp.fontSize = 28;
        tmp.alignment = TextAlignmentOptions.Center;
        tmp.color = Color.white;
        
        return button;
    }

    static GameObject CreateText(Transform parent, string name, string text, Vector2 position, Vector2 size, int fontSize = 24)
    {
        GameObject textObj = new GameObject(name);
        textObj.transform.SetParent(parent, false);
        
        RectTransform rect = textObj.AddComponent<RectTransform>();
        rect.anchoredPosition = position;
        rect.sizeDelta = size;
        
        TextMeshProUGUI tmp = textObj.AddComponent<TextMeshProUGUI>();
        tmp.text = text;
        tmp.fontSize = fontSize;
        tmp.alignment = TextAlignmentOptions.Center;
        tmp.color = Color.white;
        
        return textObj;
    }

    static GameObject CreateInputField(Transform parent, string name, string placeholder, Vector2 position, Vector2 size)
    {
        GameObject inputObj = new GameObject(name);
        inputObj.transform.SetParent(parent, false);
        
        RectTransform rect = inputObj.AddComponent<RectTransform>();
        rect.anchoredPosition = position;
        rect.sizeDelta = size;
        
        Image image = inputObj.AddComponent<Image>();
        image.color = new Color(1f, 1f, 1f, 0.2f);
        
        TMP_InputField inputField = inputObj.AddComponent<TMP_InputField>();
        
        // 创建文本区域
        GameObject textArea = new GameObject("Text Area");
        textArea.transform.SetParent(inputObj.transform, false);
        RectTransform textAreaRect = textArea.AddComponent<RectTransform>();
        textAreaRect.anchorMin = Vector2.zero;
        textAreaRect.anchorMax = Vector2.one;
        textAreaRect.sizeDelta = new Vector2(-20, -20);
        textArea.AddComponent<RectMask2D>();
        
        // 创建占位符文本
        GameObject placeholderObj = new GameObject("Placeholder");
        placeholderObj.transform.SetParent(textArea.transform, false);
        RectTransform placeholderRect = placeholderObj.AddComponent<RectTransform>();
        placeholderRect.anchorMin = Vector2.zero;
        placeholderRect.anchorMax = Vector2.one;
        placeholderRect.sizeDelta = Vector2.zero;
        TextMeshProUGUI placeholderText = placeholderObj.AddComponent<TextMeshProUGUI>();
        placeholderText.text = placeholder;
        placeholderText.fontSize = 24;
        placeholderText.color = new Color(1f, 1f, 1f, 0.5f);
        
        // 创建输入文本
        GameObject textObj = new GameObject("Text");
        textObj.transform.SetParent(textArea.transform, false);
        RectTransform textRect = textObj.AddComponent<RectTransform>();
        textRect.anchorMin = Vector2.zero;
        textRect.anchorMax = Vector2.one;
        textRect.sizeDelta = Vector2.zero;
        TextMeshProUGUI inputText = textObj.AddComponent<TextMeshProUGUI>();
        inputText.fontSize = 24;
        inputText.color = Color.white;
        
        inputField.textViewport = textAreaRect;
        inputField.textComponent = inputText;
        inputField.placeholder = placeholderText;
        
        return inputObj;
    }

    static void CreateLoginPanel(Transform parent)
    {
        GameObject panel = CreatePanel(parent, "LoginPanel", true);
        
        CreateText(panel.transform, "TitleText", "五子棋游戏", new Vector2(0, 200), new Vector2(400, 80), 36);
        CreateInputField(panel.transform, "UsernameInput", "请输入用户名", new Vector2(0, 50), new Vector2(400, 60));
        CreateInputField(panel.transform, "PasswordInput", "请输入密码", new Vector2(0, -50), new Vector2(400, 60));
        CreateButton(panel.transform, "LoginButton", "登录", new Vector2(0, -150), new Vector2(200, 60));
    }

    static void CreateMainMenuPanel(Transform parent)
    {
        GameObject panel = CreatePanel(parent, "MainMenuPanel");
        
        CreateText(panel.transform, "UserInfoText", "玩家信息", new Vector2(0, 200), new Vector2(400, 100), 24);
        CreateButton(panel.transform, "MatchButton", "开始匹配", new Vector2(0, 0), new Vector2(300, 80));
        CreateButton(panel.transform, "QuitButton", "退出游戏", new Vector2(0, -150), new Vector2(200, 60));
    }

    static void CreateMatchingPanel(Transform parent)
    {
        GameObject panel = CreatePanel(parent, "MatchingPanel");
        
        CreateText(panel.transform, "MatchingText", "正在匹配中...", new Vector2(0, 50), new Vector2(400, 80), 32);
        CreateButton(panel.transform, "CancelButton", "取消匹配", new Vector2(0, -100), new Vector2(200, 60));
    }

    static void CreateGamePanel(Transform parent)
    {
        GameObject panel = CreatePanel(parent, "GamePanel");
        
        // 创建棋盘容器
        GameObject boardContainer = new GameObject("BoardContainer");
        boardContainer.transform.SetParent(panel.transform, false);
        RectTransform boardRect = boardContainer.AddComponent<RectTransform>();
        boardRect.anchoredPosition = new Vector2(-300, 0);
        boardRect.sizeDelta = new Vector2(750, 750);
        boardContainer.AddComponent<GameBoard>();
        boardContainer.AddComponent<BoardClickHandler>();
        
        // 添加背景
        Image boardBg = boardContainer.AddComponent<Image>();
        boardBg.color = new Color(0.87f, 0.72f, 0.53f, 1f); // 木色
        
        // 创建棋盘和棋子父对象
        GameObject boardParent = new GameObject("BoardParent");
        boardParent.transform.SetParent(boardContainer.transform, false);
        RectTransform boardParentRect = boardParent.AddComponent<RectTransform>();
        boardParentRect.anchorMin = Vector2.zero;
        boardParentRect.anchorMax = Vector2.one;
        boardParentRect.sizeDelta = Vector2.zero;
        
        GameObject pieceParent = new GameObject("PieceParent");
        pieceParent.transform.SetParent(boardContainer.transform, false);
        RectTransform pieceParentRect = pieceParent.AddComponent<RectTransform>();
        pieceParentRect.anchorMin = Vector2.zero;
        pieceParentRect.anchorMax = Vector2.one;
        pieceParentRect.sizeDelta = Vector2.zero;
        
        // 创建信息面板
        GameObject infoPanel = new GameObject("InfoPanel");
        infoPanel.transform.SetParent(panel.transform, false);
        RectTransform infoRect = infoPanel.AddComponent<RectTransform>();
        infoRect.anchoredPosition = new Vector2(450, 200);
        infoRect.sizeDelta = new Vector2(400, 300);
        
        CreateText(infoPanel.transform, "GameInfoText", "游戏信息", new Vector2(0, 100), new Vector2(350, 50), 24);
        CreateText(infoPanel.transform, "TurnInfoText", "回合信息", new Vector2(0, 30), new Vector2(350, 50), 24);
        CreateText(infoPanel.transform, "OpponentText", "对手信息", new Vector2(0, -40), new Vector2(350, 50), 24);
        
        CreateButton(panel.transform, "SurrenderButton", "投降", new Vector2(450, -200), new Vector2(150, 60));
        CreateButton(panel.transform, "BackButton", "返回", new Vector2(450, -300), new Vector2(150, 60));
    }

    static void CreateGameOverPanel(Transform parent)
    {
        GameObject panel = CreatePanel(parent, "GameOverPanel");
        
        // 设置更透明的背景
        Image image = panel.GetComponent<Image>();
        image.color = new Color(0f, 0f, 0f, 0.8f);
        
        CreateText(panel.transform, "ResultText", "游戏结果", new Vector2(0, 50), new Vector2(500, 100), 36);
        CreateButton(panel.transform, "BackToMenuButton", "返回主菜单", new Vector2(0, -100), new Vector2(250, 60));
    }

    static void CreateMessagePanel(Transform parent)
    {
        GameObject panel = new GameObject("MessagePanel");
        panel.transform.SetParent(parent, false);
        
        RectTransform rect = panel.AddComponent<RectTransform>();
        rect.anchoredPosition = new Vector2(0, 400);
        rect.sizeDelta = new Vector2(600, 100);
        
        Image image = panel.AddComponent<Image>();
        image.color = new Color(0f, 0f, 0f, 0.8f);
        
        CreateText(panel.transform, "MessageText", "", Vector2.zero, new Vector2(550, 80), 28);
        
        panel.SetActive(false);
    }
}
#endif
